﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Security;
using InformationCenter.Models;
using InformationCenter.SQLHelper;
using Newtonsoft.Json;

namespace InformationCenter.Controllers
{
    public class BaseController : Controller
    {
        protected UserInfo CurrentUser;
        private void CheckLogin()
        {
            if (Session["User"] == null)
            {
                //read user from db,key by Auth cookie
                if (!User.Identity.IsAuthenticated) return;
                var db = new WebDbContext();
                CurrentUser = db.UserInfos.FirstOrDefault(p => p.Name==User.Identity.Name);
                if (CurrentUser != null)
                {
                    Session["User"] = CurrentUser;
                }
            }
            else
            {
                CurrentUser = Session["User"] as UserInfo;
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            CheckLogin();
            base.OnActionExecuting(filterContext);
        }
    }
    public class HomeController : BaseController
    {
        // GET: Home
        [System.Web.Mvc.Authorize]
        public ActionResult Index(FormCollection getCollection)
        {
            //var user = getCollection["username"];
            //var pwd = getCollection["password"];
            //if (user == "sora")
            //{
            //    FormsAuthentication.SetAuthCookie(user, false);
            //    return View();
            //}
            ViewBag.MenuInfo = CurrentUser==null?"Need login":CurrentUser.Nickname;

            return View();
        }

        [System.Web.Mvc.HttpPost]
        public ActionResult Login(UserLogin login)
        {
            UserInfo user;
            using (var db= new WebDbContext())
            {
                 user = db.UserInfos.FirstOrDefault(p => p.Name == login.UserName && p.Password == login.Password);
                if (user == null)
                {
                    ModelState.AddModelError("Error", "用户名或密码错误！"); //前面是key 作为标示用的,后面是输出字,前台调用@Html.ValidationMessage("Error")
                    return View(login);
                }

                user.Logincount = user.Logincount + 1;
                db.SaveChanges();
            }
 
            if (user.Locked)
            {
                ModelState.AddModelError("Error", "该用户已被锁定,请联系管理员");
                return View(login);
            }

            //验证账号密码
                FormsAuthentication.SetAuthCookie(login.UserName, false); //验证成功
     
                 Session["User"] = user;
                return RedirectToAction("Index", "Home");

        }

        public ActionResult Login()
        {
            return View();
        }

    }
}
